package util

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"crypto/x509"
	"strings"

	// "encoding/base64"
	"encoding/hex"
	"fmt"
	// "strings"
)

func GenerateKeyPair() (string, string, string, error) {
	// 生成 ECDSA 密钥对
	privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Println("Error generating ECDSA key:", err)
		return "", "", "", err
	}
	// 将私钥的 D（私钥部分）序列化为字节数组
	privateKeyBytes := privateKey.D.Bytes()
	StrPrivate := hex.EncodeToString(privateKeyBytes)

	// 计算私钥的 SHA-256 哈希值
	hash := sha256.Sum256(privateKeyBytes)

	// 将哈希值转换为十六进制字符串
	StrSha256Private := hex.EncodeToString(hash[:])

	// 从私钥中提取公钥
	publicKey := privateKey.PublicKey

	publicKeyBytes, err := x509.MarshalPKIXPublicKey(&publicKey)
	if err != nil {
		fmt.Println("Error marshaling public key:", err)
		return "", "", "", err
	}
	StrPublic := hex.EncodeToString(publicKeyBytes)

	return StrPrivate, StrSha256Private, StrPublic, nil
}

func URLencode(s string) string {
	return strings.ReplaceAll(s, " ", "%20")
	// return base64.StdEncoding.EncodeToString([]byte(s))
	// return s
}
